package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final String KEY_PREFIX = "user:verify:phone";

    public Boolean check(String data, Integer type) {
        User record = new User();
        switch (type){
            case 1:
                // 用户名称设置
                record.setUsername(data);
                break;
            case 2:
                // 手机号
                record.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        // 执行查询
        // User user = userMapper.selectOne(record); // 不要这样做
        int count = userMapper.selectCount(record);
        // 如果没有找到，说明数据可以使用返回true
        return count == 0;
    }

    public void sendCode(String phone) {
        // 1、校验手机号码格式
        if(!RegexUtils.isPhone(phone)){
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        // 2、生成随机验证码
        String code = RandomStringUtils.randomNumeric(6);
        System.out.println("验证码："+ code);

        // 3、保存到redis：有效期是5分钟
        String key = KEY_PREFIX + phone;
        redisTemplate.opsForValue().set(key ,code , 5, TimeUnit.MINUTES);

        // 4、发送一条消息到mq：通知短信微服务发短信
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }



    /**
     * 用户注册
     * @param userDTO  用户DTO
     * @param code  页面传入的验证码
     */
    public void register(UserDTO userDTO, String code) {
        // 1、判断两次密码是否一致
        if(!StringUtils.equals(userDTO.getPassword(),userDTO.getConfirmPassword())){
            throw new LyException(ExceptionEnum.INVALID_PASSWORD_ERROR);
        }
        // 2、判断验证码是否一致
        String key = KEY_PREFIX + userDTO.getPhone();
        String cacheCode = redisTemplate.opsForValue().get(key);
        if(!StringUtils.equals(cacheCode, code)){
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        // 3、对密码进行加密：BCrypt加密
        User user = BeanHelper.copyProperties(userDTO, User.class);
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 4、保存
        int count = userMapper.insertSelective(user);
        if(count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        // 根据用户名称查询用户
        if(!RegexUtils.isVerifyUsername(username)){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        User record = new User();
        record.setUsername(username);
        User user = userMapper.selectOne(record);
        if(user == null || !passwordEncoder.matches(password, user.getPassword())){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        // 返回
        return BeanHelper.copyProperties(user, UserDTO.class);
    }
}
